//
//  ST_TIANVoiceEngagementController.swift
//  btvideo
//
//  Created by Jason on 2021/8/4.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SDWebImage
import SwiftyUserDefaults
import NERtcSDK


class ST_TIANVoiceEngagementController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .black
        
        self.title_nav_btn.setTitleForAllStates("语言连麦")
        
        self.right_tool_control.setBottomBtn(normalTitle: "免提关", selectedTitle: "免提开", normalImage: ST_ImageUtils.imageName("chat_right_bar_bottom_icon")!, selectedImage: ST_ImageUtils.imageName("chat_right_bar_bottom_icon_sel")!)
        
        self.right_tool_control.bottomClosure = { f in
            
            ST_TIANEngagementManager.defaultManager.agoraKit.setLoudspeakerMode(f)
        }
        
        view.addSubview(back_image_view)
        back_image_view.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(ScreenHeight)
        }
        
        setup_calling_u_i()
        
        setup_bootom_tool_bar()
        
        set_up_custom_navigation_bar()
        
        bottom_tool_control.alpha = 1
        
        right_tool_control.alpha = 1
        
        layout_univalence_view()
        
        bind_talk_user_info()
    }
    
    deinit {
        
        print("语音通话界面释放啦🌶")
        
        ST_TIANEngagementManager.defaultManager.destroy()
    }
    
    
    //    MARK: - Setup UI
    
    func layout_univalence_view(){
        
        guard let entity = engagement_entiy, ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex != .female else{
            return
        }
        
        
        self.view.addSubview(self.univalence_control)
        self.univalence_control.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(35+44+statusBarHeight)
            make.height.equalTo(28)
        }
        
        self.univalence_control.univalence = entity.channelPrice * 60
        
        
        
        
    }
    
    
    fileprivate func set_up_custom_navigation_bar()  {
        
        
        view.addSubview(own_navigation_bar)
        own_navigation_bar.snp.makeConstraints { (make) in
            make.right.left.top.equalTo(view)
            make.height.equalTo(statusBarHeight+44)
        }
        own_navigation_bar.addSubview(left_nav_btn)
        own_navigation_bar.addSubview(title_nav_btn)
        own_navigation_bar.addSubview(right_nav_btn)
        
        left_nav_btn.snp.makeConstraints { (make) in
            make.left.equalTo(own_navigation_bar).offset(8)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        right_nav_btn.snp.makeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-14)
            make.bottom.equalTo(own_navigation_bar)
            make.width.height.equalTo(44)
        }
        
        title_nav_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(left_nav_btn)
            make.centerX.equalTo(own_navigation_bar)
        }
        
    }
    
    
    fileprivate func setup_calling_u_i(){
        
        view.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(avatar_image_view_width)
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(44+statusBarHeight+78)
        }
        
        
        view.addSubview(nickname_label)
        nickname_label.snp.makeConstraints { (make) in
            make.height.equalTo(TIANCompatibleValue(value: 29))
            make.centerX.equalToSuperview()
            make.top.equalTo(avatar_image_view.snp.bottom).offset(30)
        }
        
        view.addSubview(talk_date_label)
        talk_date_label.snp.makeConstraints { (make) in
            make.height.equalTo(TIANCompatibleValue(value: 20))
            make.centerX.equalToSuperview()
            make.top.equalTo(nickname_label.snp.bottom).offset(10)
        }
        
        if let e = engagement_entiy?.isReceived, e == true {
            talk_date_label.text = "连接中..."
        }else{
            talk_date_label.text = "正在等待对方接受邀请..."
        }
        
       
        
    }
    
    func setup_bootom_tool_bar(){
        
        
        view.addSubview(bottom_tool_control)
        bottom_tool_control.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(60+10+20+15+BTSafeAreaBottom)
        }
        
        view.addSubview(right_tool_control)
        right_tool_control.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-17)
            make.top.equalToSuperview().offset(84-20+statusBarHeight)
            make.width.equalTo(40)
            make.height.equalTo(119+50)
        }
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male {
            
            view.addSubview(rule_control)
            rule_control.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(48)
                make.right.equalToSuperview().offset(-47)
                make.height.equalTo(ST_EngagementMaleRuleView.height)
                make.bottom.equalTo(bottom_tool_control.snp.top).offset(-60)
            }
        }
        
        
        if engagement_manager.displayIncomeControl{
            
            view.addSubview(income_control)
            income_control.snp.makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.top.equalToSuperview().offset(20+44+statusBarHeight)
                make.height.equalTo(28)
            }
        }else{
            
            view.addSubview(free_talk_control)
            free_talk_control.snp.makeConstraints { (make) in
                make.centerX.equalToSuperview()
                make.top.equalToSuperview().offset(20+44+statusBarHeight)
                make.height.equalTo(28)
            }
            
        }
        
        view.addSubview(give_persent_display_label)
        give_persent_display_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(48)
            make.bottom.equalTo(bottom_tool_control.snp.top).offset(TIANCompatibleValue(value: -51))
        }
        
    }
    
    func bind_talk_user_info(){
        
        guard let entity = engagement_entiy, let nickname = entity.oppositeNickname,let avatar = entity.oppositeAvatar else { return  }
        
        bind_avatar_with_nickname(avatar: avatar, nickname: nickname)
        
    }
    
    /*
    fileprivate func fetch_opposite_user_info(){
        
        guard let entity = engagement_entiy else{
            return
        }
        
        JVrequest(PH.fetchSomeoneInfoApi,parameters: ["target_accid":entity.sessionId]) { (json) in
            
            let info = json["data"]
            
            self.bind_avatar_with_nickname(avatar: info["avatar"].stringValue, nickname: info["nickname"].stringValue)
            
        } failure: { (code, err) in
            
            self.toast(text: err)
        }
    }
     */
    
    fileprivate func bind_avatar_with_nickname(avatar:String,nickname:String){
        
        
        self.avatar_image_view.pin_setImage(from: avatar.compress_small_image(width: avatar_image_view_width*3).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        self.nickname_label.text = nickname
        
    }
    //    MARK: - Properties
    fileprivate lazy var backImage = ST_ImageUtils.imageName("碰一碰背景")
    fileprivate lazy var back_image_view:UIImageView = {
       let control = UIImageView.init(image: backImage)
       return control
   }()
    
    
    fileprivate lazy var fly_back_image_view:UIImageView = {
       let control = UIImageView()
        control.addSubview(suspend_countdown_view)
        suspend_countdown_view.snp.makeConstraints { make in
            make.width.height.equalTo(62)
            make.center.equalToSuperview()
        }
       return control
   }()
    
    
    
     fileprivate lazy var avatar_image_view_width = TIANCompatibleValue(value: 128)
    
     fileprivate lazy var avatar_image_view:UIImageView = {
           let control = UIImageView()
            control.contentMode = .scaleAspectFill
            control.cornerRadius = self.avatar_image_view_width/2.0
            control.borderColor = .white
            control.borderWidth = 2
            return control
    }()
    
     fileprivate lazy var nickname_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: TIANCompatibleValue(value: 21), weight: UIFont.Weight.medium)
        return control
    }()
     
    fileprivate lazy var talk_date_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: TIANCompatibleValue(value: 14), weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate var engagement_manager:ST_TIANEngagementManager{
        return ST_TIANEngagementManager.defaultManager
    }
    
    
    fileprivate var agoraKit:NERtcEngine?{
        return NERtcEngine.shared()
    }
    
    fileprivate var engagement_entiy:ST_TIANEngagementEntiy?{
        return ST_TIANEngagementManager.defaultManager.engagement_entiy
    }
    
    
    
    
    fileprivate lazy var own_navigation_bar:UIView = {
        let control = UIView()
        control.backgroundColor = .clear
        return control
    }()
    fileprivate lazy var left_btn_image = ST_ImageUtils.imageName("返回_white")
    
    fileprivate lazy var left_btn_suspend_image = ST_ImageUtils.imageName("返回_white_suspend")
    
    
    private var isTalking:Bool?
    
    fileprivate lazy var left_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setImage(left_btn_image, for: UIControl.State.normal)
    
        control.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
        
        //        control.backgroundColor = Color.random
        
        control.addTarget(self, action: #selector(left_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var right_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleForAllStates("举报")
        //        control.cornerRadius = 18
         
        //        control.setTitleForAllStates("帮助")
        control.setTitleColorForAllStates(.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.addTarget(self, action: #selector(right_click), for: UIControl.Event.touchUpInside)
        control.alpha = 0
        return control
    }()
    
    lazy var title_nav_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.setTitleColorForAllStates(.white)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold)
        
        control.addTarget(self, action: #selector(title_click), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    fileprivate lazy var information_label:UILabel = {
        let control = UILabel.init()
        control.textColor = UIColor.white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: TIANCompatibleValue(value: 14), weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var suspend_countdown_view:ST_SuspendVoiceCountdownView = {
        let control = ST_SuspendVoiceCountdownView()
        return control
    }()
    
    fileprivate lazy var video_filter_view:UIView = {
        let control = UIView()
        control.isHidden = true
        return control
    }()
    
    lazy var univalence_control:ChatUnivalenceControl = {
        
        let control = ChatUnivalenceControl()
        
        return control
    }()
    
    
    fileprivate lazy var match_title_label:UILabel = {
        let control = UILabel.init()
        control.textColor = .white
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate lazy var match_content_label:UILabel = {
        let control = UILabel.init()
        //        control.text = "伴心酱正在帮你寻找在线视频速配的人呢\n请耐心等待哦~"
        control.textColor = .white
        control.numberOfLines = 2
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    lazy var right_tool_control:EngagementChatRightToolControl = {
        let control = EngagementChatRightToolControl()
        control.alpha = 0
        
        control.topClosure = {[weak self] f in
            
            self?.agoraKit?.enableLocalAudio(f)
            
        }
        return control
    }()
    
    lazy var give_persent_display_label:ST_EngagementCenterInfoView = {
        let control = ST_EngagementCenterInfoView()
        return control
    }()
    
    
    lazy var rule_control:ST_EngagementMaleRuleView = {
        return ST_EngagementMaleRuleView()
    }()
    
    lazy var income_control:ST_ChatIncomeControl = {
        
        let control = ST_ChatIncomeControl()
        control.alpha = 0
        return control
    }()
    
    
    lazy var free_talk_control:ChatFreeControl = {
        
        let control = ChatFreeControl()
        control.alpha = 0
        return control
    }()
    
    
    lazy var impression_talk_control:ST_FirstImpressionCountdownView = {
        
        let control = ST_FirstImpressionCountdownView()
        
        return control
    }()
    
    
    
    lazy var bottom_tool_control:ST_EngagementChatBottomToolControl = {
        let control = ST_EngagementChatBottomToolControl()
        control.alpha = 0
        
        control.centerClosure = {[weak self] in
            
            ST_RechargeViewController.toast()
            
        }
        
        control.left_closure = {[weak self] _ in
            
            self?.close_click()
        }
        
        control.right_closure = {_ in
            
            ST_TIANEngagementManager.defaultManager.push_gift_controller()
        }
        
        return control
    }()
    
    
    lazy var report_tool_control:ST_EngagementReportChatBottomToolControl = {
        
        let control = ST_EngagementReportChatBottomToolControl()
        
        if let entity = engagement_entiy{
            
            control.type = entity.chatType.rawValue
            
            control.targetAccid = entity.sessionId
        }
        
        return control
    }()
    
    
    fileprivate lazy var hung_up_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("hungUp_icon"))
        return control
    }()
    
    
    
    fileprivate lazy var doubt_label_times = 0
    /**
     疑问提示
     */
    fileprivate lazy var doubt_label:UILabel = {
        let control = UILabel()
        control.cornerRadius = 3
        control.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
        control.textColor = .white
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.textAlignment = .center
        return control
    }()
    
    fileprivate var floating_recover_transform:CGAffineTransform?
}

//MARK: - Event
extension ST_TIANVoiceEngagementController{
    
    @objc func close_click(){
        
        
        self.engagement_manager.leave()
        
        self.goback_previous_controller()
        
    }
    
    @objc func left_click(){
        
        
        if let state = isTalking{
            
            //           正在通话中 小窗
            if state{
                
                print("开启小窗")
                
                engagement_manager.isSuspended = true
                
                let config = ST_SwiftyWidgetConfig(animationDuration: 0.25, floatingDefaultPoint: CGPoint(x: 0, y: 100), floatingDefaultSize: CGSize(width: 78, height: 80), floatingWindowRadious: 14, window_content_edge: UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8), window_background_color: #colorLiteral(red: 0.9411764706, green: 0.9411764706, blue: 0.9411764706, alpha: 1))
                
                ST_SwiftyFloatingWidget.provider.floating(config: config, controller: self)
               
            }
            //                结束通话
            else{
                
                self.goback_previous_controller()
                
//                KC_Router.pop()
                print("#3854 结束通话")
            }
            
        }
        //            未接通，离开频道 并且退出界面
        else{
            
            print("#3854 离开频道 并且退出界面")
            
            self.engagement_manager.leave()
            
            self.goback_previous_controller()
        }
        
    }
    
    @objc func title_click(){
        
        
        
    }
    
    @objc func right_click(){
        
        guard let entity = self.engagement_entiy else { return  }
        
        let vc = ST_ReportPersonController()
        
        vc.userId = entity.sessionId
        
        let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
        
        GlobalPresent(toController: nav)
        
    }
    
    
    
}


extension ST_TIANVoiceEngagementController:ST_TIANEngagementLayoutUIProtocol{
    func engagementMyCurrentFreeSeconds(seconds: Int) {
        if seconds < 1{
            self.free_talk_control.alpha = 0
        }else{
            self.free_talk_control.text = "剩余"+seconds.string+SCComponets.rich_text_storage_component.json["engagement_figure"]["f_seconds"].stringValue
            self.free_talk_control.alpha = 1
        }
        
    }
    
    
    func engagementMyCurrentImpression(currentSeconds:Int,haveState:Bool){
        
        if !haveState{
            return
        }
        
        if currentSeconds > 0{
            
            if impression_talk_control.superview == nil{
                view.addSubview(impression_talk_control)
                impression_talk_control.snp.makeConstraints { make in
                    make.bottom.equalToSuperview().offset(-168+34-BTSafeAreaBottom)
                    make.centerX.equalToSuperview()
                    make.width.equalTo(259+33)
                    make.height.equalTo(66)
                }
            }
            
        }else{
            
            give_persent_display_label.display_impression_hint()
        }
        
    }
    
    func engagementIncrease(value: ST_TIANEngagementTargetSpendType) {
        
        
        switch value {
        case .free(let seconds):
            self.income_control.alpha = 1
            self.income_control.text = seconds.string + SCComponets.rich_text_storage_component.json["engagement_figure"]["f_unit"].stringValue
        case .reducingValue(let integral):
            self.income_control.alpha = 1
            self.income_control.text = String(format: "已产生%0.2f\(Defaults[.PandaStr])" + SCComponets.rich_text_storage_component.json["engagement_figure"]["shouye"].stringValue, integral)
        }
        
        
    }
    
    func engagementReceivedGift(str: String) {
        
        give_persent_display_label.receive(giftStr: str)
        
    }
    
    
    func engagementStateUpdate(state: ST_EngagementStatus) {
        
        switch state {
        
        case .talking:
            
            left_nav_btn.isUserInteractionEnabled = false
            bottom_tool_control.left_btn.isUserInteractionEnabled = false
            main_thread_execute(afterDelay: 2) {
                self.bottom_tool_control.left_btn.isUserInteractionEnabled = true
                self.left_nav_btn.isUserInteractionEnabled = true
            }
            
            univalence_control.removeFromSuperview()
            
            self.rule_control.alpha = 0
            
            ST_MediaChatDispatcher.shared.stop_waiting_voice()
            
            left_nav_btn.setImage(left_btn_suspend_image, for: .normal)
            
            self.right_nav_btn.alpha = 1
            
//            fetch_opposite_user_info()
            self.isTalking = true

        case .hungUp:
            
            self.isTalking = false
            
            left_nav_btn.setImage(left_btn_image, for: .normal)
            
            engagementHiddenDoubt()
            
            ST_LiveBeautyWidget.shared.cancel_match_game()
            
            self.rule_control.removeFromSuperview()
            self.bottom_tool_control.removeFromSuperview()
            self.right_tool_control.removeFromSuperview()
            
            self.give_persent_display_label.removeFromSuperview()
            
            self.impression_talk_control.removeFromSuperview()
            
            
            if self.right_nav_btn.alpha == 1{
                view.addSubview(report_tool_control)
                report_tool_control.snp.makeConstraints { (make) in
                    make.bottom.left.right.equalToSuperview()
                    make.height.equalTo(132+BTSafeAreaBottom)
                }
                
//            }else{
//                self.left_click()
            }
            
        //            AgoraRtcEngineKit.destroy()
        
        default:
            break
        }
        
    }
   
    
    func engagementOtherPartyHangsUp() {
        
        view.addSubview(hung_up_image_view)
        hung_up_image_view.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        
        main_thread_execute(afterDelay: 1.7) {
            self.hung_up_image_view.removeFromSuperview()
        }
    }
    
    func engagementDoubtLayout(isMe: Bool) {
        
        doubt_label_times += 1
        
        if doubt_label_times < 3{
            return
        }
        
        var str = ""
        
        if isMe{
            
            str = SCComponets.rich_text_storage_component.json["engagement_figure"]["f_toast"][0].stringValue
            
        }else{
            
            str = SCComponets.rich_text_storage_component.json["engagement_figure"]["f_toast"][1].stringValue
            
        }
        
        let h = str.width(withConstrainedHeight: 100, font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)) + 10
        
        if doubt_label.superview == nil{
            
            view.addSubview(doubt_label)
            doubt_label.snp.makeConstraints { (make) in
                make.width.equalTo(h)
                make.height.equalTo(20)
                make.center.equalToSuperview()
            }
            
        }else{
            doubt_label.snp.makeConstraints { (make) in
                make.width.equalTo(h)
            }
        }
        
        doubt_label.text = str
        
        doubt_label.alpha = 1
    }
    
    func engagementHiddenDoubt() {
        doubt_label.alpha = 0
        doubt_label_times = 0
    }
    
    func engagementCurrentSeconds(seconds: Int) {
        
        if seconds == -1{
            give_persent_display_label.alpha = 0
            return
        }
        let date = seconds_to_hours_minutes_seconds(seconds: seconds)
        
        let hours = date.hour
        
        let minutes = date.minute
        
        let secondsInt = date.second
        
        if hours > 0{
            secondsDisplayLoop(str: String(format: "%02d:%02d:%02d", hours,minutes,secondsInt))
        }else{
            secondsDisplayLoop(str: String(format: "%02d:%02d", minutes,secondsInt))
        }
        
        give_persent_display_label.setCurrentTime(seconds: seconds)
    }
    
    func engagementAlert(text: String) {
        
        self.toast(text: text)
        
    }
    
    fileprivate func secondsDisplayLoop(str: String) {
        
        suspend_countdown_view.bind(seconds: str)
        
//        bottom_tool_control.update_left_button(title: str)
        
        talk_date_label.text = str
        
        information_label.text = ""
        
        
        
        
    }
    
}

//MARK: - ST_SuspendProcessorProtocol
extension ST_TIANVoiceEngagementController:ST_ST_SwiftyFloatingWidgetProtocol{
    
    func swiftyFloatingShareView() -> UIView {
        /// 小窗和初体验冲突问题
        return fly_back_image_view
    }
    
    func swiftyRecoverComplete() {
        
        view.isUserInteractionEnabled = true
        
        engagement_manager.isSuspended = false

    }
    
    func swiftyFloatingCanRecover() -> Bool {
        
        /// 没有一个不等于空的 自动隐藏的Controller
        return (ST_GlobalAutoDismissDistributor.distributor.autoDismissControllerCollection.contains(where: { $0.value != nil }) == false)
        
    }
}


extension ST_TIANVoiceEngagementController:ST_RefuseMediaInviteProtocol{
    
    func refuseMe(text:String)  {
        
        talk_date_label.text = text
        
        main_thread_execute(afterDelay: 1) {
            
            
//            if text.contains("拒绝") || text.contains("忙线"){
//                self.pushPathStr = "对方拒绝消息"
//            }
            self.engagement_entiy?.targetRefuseMe = true
            
            self.left_click()
        }
        
        
    }
}
